package com.example.controller;

import com.example.common.Result;
import com.example.entity.SDistrict;
import com.example.service.SDistrictService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 查询可选地址
 */
@RestController
@Slf4j
@RequestMapping("/sDistrict")
public class SDistrictController {
    @Autowired
    private SDistrictService sDistrictService;
    @Autowired
    private RedisTemplate<String, SDistrict> redisTemplate;
    private static final String ADDRESS_KEY = "address";

    @GetMapping
    public Result<List<SDistrict>> findAddress() {
        log.info("查询可选地址");
        List<SDistrict> sDistrictList = redisTemplate.opsForList().range(ADDRESS_KEY, 0, -1);
        if(sDistrictList!=null && !sDistrictList.isEmpty()){
            return Result.success(sDistrictList);
        }
        sDistrictList = sDistrictService.findAll();
        if(sDistrictList != null && !sDistrictList.isEmpty()){
            redisTemplate.opsForList().rightPushAll(ADDRESS_KEY, sDistrictList);
            redisTemplate.expire(ADDRESS_KEY, 1, TimeUnit.DAYS);
        }
        return Result.success(sDistrictList);
    }
}
